package com.gujiangbo.thread;

import org.junit.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class TimeUnitTest {

    @Test
    public void timeUnitTest() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " is starting");
        }, "t1");
        System.out.println("----main start---");
        TimeUnit.SECONDS.sleep(3);
        Thread thread = Thread.currentThread();
        thread.interrupt();
        t1.start();
        System.out.println("----main end-----");
    }

    /**
     * 设定优先级
     */
    @Test
    public void threadGroupTest() {
        ThreadGroup threadGroup = new ThreadGroup("gujiangbo");
        threadGroup.setMaxPriority(7);
        Thread t1 = new Thread(threadGroup, "t1");
        t1.setPriority(9);
        t1.start();
        System.out.println(t1.getPriority());
        System.out.println(threadGroup.getParent().getName());
        System.out.println(t1.getThreadGroup().getName());

    }

    /**
     * interrupt
     */
    @Test
    public void interrupttest() throws Exception {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.MINUTES.sleep(3);
            } catch (InterruptedException e) {
                System.out.println("current thread is interrupted");
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(4);
        thread.interrupt();
    }


    @Test
    public void joinTest() throws InterruptedException {
        List<Thread> threads = IntStream.range(1, 3).mapToObj(TimeUnitTest::create).collect(Collectors.toList());
        threads.forEach(Thread::start);

        for (Thread thread : threads) {
            thread.join();
        }

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "#" + i);
            shortSleep();
        }

    }

    private static Thread create(int seq) {
        return new Thread(() -> {
            IntStream.range(1, 10).forEach(v -> {
                System.out.println(Thread.currentThread().getName() + "#" + v);

            });
        }, String.valueOf(seq));
    }

    private static void shortSleep() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
